package com.qf.fmall.orders.service.impl;

import com.qf.fmall.orders.entity.OrderItem;
import com.qf.fmall.orders.entity.Orders;
import com.qf.fmall.orders.mapper.OrderItemDao;
import com.qf.fmall.orders.mapper.OrdersDao;
import com.qf.fmall.orders.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductSkuDao;
import com.qf.fmall.shopcart.entity.ShoppingCart;
import com.qf.fmall.shopcart.service.IShoppingCartService;
import com.qf.fmall.utils.WxPayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author dongjl
 * @since 2024-01-18
 */
@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersDao, Orders> implements IOrdersService {

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private ProductSkuDao productSkuDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Override
    public HashMap<String, Object> add(List<String> cids, Orders orders) throws ParseException {

        //1. 考虑购买商品的库存是否足够，够的话扣减库存，如果不够，抛出异常
        List<ShoppingCart> carts = shoppingCartService.listbycids(cids);
        for (ShoppingCart cart : carts) {

            // 购买量
            String cartNum = cart.getCartNum();
            // 库存量
            Integer stock = cart.getStock();
            if (Integer.valueOf(cartNum)<=stock) {
                // 扣减库存
                String skuId = cart.getSkuId();
                ProductSku productSku = new ProductSku();
                productSku.setSkuId(Integer.valueOf(skuId));
                productSku.setStock(stock-Integer.valueOf(cartNum));
                productSkuDao.updateById(productSku);
            }else {
                // 库存不足
                log.info("库存不足");
                throw new RuntimeException("商品库存不足，下单失败");
            }

        }

        //2. 向 orders表写入数据
        //2.1 生成订单ID
        String orderID = UUID.randomUUID().toString().replaceAll("-", "");
        orders.setOrderId(orderID);
        // 处理订单中的商品名称
        StringBuffer stringBuffer = new StringBuffer();
        for (ShoppingCart cart : carts) {
            String productName = cart.getProductName();
            stringBuffer.append(productName);
            stringBuffer.append(",");
        }
        String productNames = stringBuffer.toString();
        orders.setUntitled(productNames);

        orders.setStatus("0"); // 订单待支付

        orders.setDeleteStatus(0);  // 订单状态为未删除
        Date date = new Date();
        orders.setCreateTime(date);
        orders.setUpdateTime(date);

        save(orders);  // 保存订单数据

        //3. 向 order_item 写入数据
        for (ShoppingCart cart : carts) {
            OrderItem orderItem = new OrderItem();
            //1. 生成主键
            String itemId = UUID.randomUUID().toString().replaceAll("-", "");
            orderItem.setItemId(itemId);
            orderItem.setOrderId(orderID);
            orderItem.setProductId(cart.getProductId()+"");
            orderItem.setProductName(cart.getProductName());
            orderItem.setProductImg(cart.getProductImg());
            orderItem.setSkuId(cart.getSkuId());
            orderItem.setSkuName(cart.getSkuName());
            orderItem.setProductPrice(cart.getProductPrice());
            orderItem.setBuyCounts(Integer.valueOf(cart.getCartNum()));
            BigDecimal totalAmount = new BigDecimal(cart.getCartNum()).multiply(cart.getProductPrice());
            orderItem.setTotalAmount(totalAmount);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date basketDate = simpleDateFormat.parse(cart.getCartTime());
            orderItem.setBasketDate(basketDate);
            orderItem.setIsComment(0);
            orderItemDao.insert(orderItem);
        }

        //4. 删除购物车中的对应的数据
        shoppingCartService.removeBatchByIds(cids);

        //5. 调用微信支付获取 支付url
        String payUrl =  getPayUrl(productNames,orderID,orders.getActualAmount());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderId",orderID);
        hashMap.put("productNames",productNames);
        hashMap.put("payUrl",payUrl);

        return hashMap;
    }

    private String getPayUrl(String productNames,String orderID,Integer totalFee) {

        // 调用微信支付平台获取可以支付的url
        String payUrl = WxPayUtils.getPayUrl(productNames, orderID, totalFee);

        return payUrl;
    }
}
